# -*- coding: utf-8 -*-
import hashlib
import json
import time

import requests
from django.conf import settings

from common.utils import track_logging
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://gateway.ybbanggo.com/gateway/api/h5Pay'

APP_CONF = {
    '06f61af274bb49608b38f83ca61dbf65': {
        'API_KEY': '1677b6430bb943f89b7027810cab618a',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s += 'paySecret=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def _get_pay_type(pay_tag):
    if pay_tag == 'alipay':
        return 'CYPAYTM', 'CYPAYTM_F2F'
    else:
        return 'CYPAYTM', 'CYPAYTM_F2F_WX'


# 修远科技 开通的是条码支付 关键点几个参数我说一下，支付宝条码 （payWayCode=CYPAYTM  requestType=CYPAYTM_F2F 限额 11元以上） 微信条码（payWayCode=CYPAYTM requestType=CYPAYTM_F2F_WX ）
# 研洋保健 开通的是支付宝wap  关键点几个参数我说一下（payWayCode=CYPAYFH  requestType=CYPAYFH_ZFB_H5 限额 20-999元）
def create_charge(pay_amount, pay_tag='weixin'):
    ''' 创建订单 '''
    app_id = '06f61af274bb49608b38f83ca61dbf65'
    api_key = _get_api_key(app_id)
    if pay_amount < 11:
        pay_amount = 11
    pay_waycode, requestType = _get_pay_type(pay_tag)
    post_data = {
        'payWayCode': pay_waycode,
        'requestType': requestType,
        'orderPrice': pay_amount,
        'orderNo': 'sk' + str(int(time.time())),
        'orderDate': local_now().strftime('%Y%m%d'),
        'orderTime': local_now().strftime('%Y%m%d%H%M%S'),
        'payKey': app_id,
        'productName': 'charge',
        'orderIp': '127.0.0.1',
        'orderPeriod': '60',
        'notifyUrl': '{}/pay/api/charge/agent_scanpay_notify/'.format(settings.NOTIFY_PREFIX),
    }
    post_data['sign'] = generate_sign(post_data, api_key)
    _LOGGER.info("agent_scan_jhzf_pay create  data: %s", post_data)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=post_data, headers=headers, timeout=30)
    _LOGGER.info("agent_scan_jhzf_pay create rdp data: %s", response.text)
    return json.loads(response.text)['payUrl']


if __name__ == '__main__':
    app_id = '06f61af274bb49608b38f83ca61dbf65'
    api_key = _get_api_key(app_id)
    post_data = {
        'payWayCode': 'CYPAYTM',
        'requestType': 'CYPAYTM_F2F',
        'orderPrice': 20,
        'orderNo': 'sk' + str(int(time.time())),
        'orderDate': time.strftime('%Y%m%d'),
        'orderTime': time.strftime('%Y%m%d%H%M%S'),
        'payKey': app_id,
        'productName': 'charge',
        'orderIp': '127.0.0.1',
        'orderPeriod': '60',
        'notifyUrl': 'http://www.baidu.com',
    }
    post_data['sign'] = generate_sign(post_data, api_key)
    print post_data
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=post_data, headers=headers, timeout=30)
    print response.text
